// import { getCoordinateString } from '../utils'

export default {
  data () {
    return {
      ysqxxStationTypeKey: {
        ysqxx_SWSW: [
          { key: 'FRGRD_TEXT', label: '报汛等级', isFull: true },
          { key: 'STCD', label: '站码', isFull: true },
          { key: 'LGTD', label: '经度', isFull: true },
          { key: 'LTTD', label: '纬度', isFull: true },
          { key: 'STTP_TEXT', label: '站类', isFull: true },
          { key: 'STLC', label: '站点地址', isFull: true }
        ],
        ysqxx_SQ: [
          { key: 'FRGRD_TEXT', label: '报汛等级', isFull: true },
          { key: 'STCD', label: '站码', isFull: true },
          { key: 'LGTD', label: '经度', isFull: true },
          { key: 'LTTD', label: '纬度', isFull: true },
          { key: 'STTP_TEXT', label: '站类', isFull: true },
          { key: 'STLC', label: '站点地址', isFull: true }
        ],
        ysqxx_SZ: [
          { key: 'STCD', label: '站码', isFull: true },
          { key: 'LGTD', label: '经度', isFull: true },
          { key: 'LTTD', label: '纬度', isFull: true },
          { key: 'STTP_TEXT', label: '站类', isFull: true },
          { key: 'STLC', label: '站点地址', isFull: true }],
        ysqxx_DXS: [
          { key: 'STCD', label: '站码', isFull: true },
          { key: 'LGTD', label: '经度', isFull: true },
          { key: 'LTTD', label: '纬度', isFull: true },
          { key: 'STTP_TEXT', label: '站类', isFull: true },
          { key: 'STLC', label: '站点地址', isFull: true },
          { key: 'DASL_TEXT', label: '深浅层名称', isFull: true }
        ]
      }
    }
  },
  methods: {
    // 选中事件处理方法
    async selectedCallback ({ selected, deselected }) {
      for (const feature of selected) {
        const data = feature.getProperties()
        console.log({ data, feature })
        if (data.features && Array.isArray(data.features)) {
          const nowZoom = this.map1.getView().getZoom()
          this.setCenterAndZoom(data.geometry.flatCoordinates, nowZoom + 2)
        } else if (data.layerId.startsWith('ysqjcdp_')) {
          return
        } else if (data.layerId.startsWith('ysqxx_')) {
          const typeKey = data.layerId.startsWith('ysqxx_CITY') ? 'ysqxx_DXS' : data.layerId
          const model = {
            title: data.STNM,
            data: this.ysqxxStationTypeKey[typeKey]?.map(item => {
              return {
                ...item,
                value: data[item.key] || ''
              }
            }),
            hasCalculate: this.$route.path.includes('/achievements')
          }
          this.createHtmlAndShow(model, feature)
        } else {
          if (!data.layerId.startsWith('station_')) return
          // 根据 data 里面的属性值动态创建 popup 里面的 html 片段
          const model = {
            // title: `${data.STNM} ${data.STCD}`,
            title: data.STNM,
            data: [
              { isFull: true, label: '测站编码', value: data.STCD || '' },
              { isFull: true, label: '河流名称', value: data.RVNM || '' },
              { isFull: true, label: '水系名称', value: data.HNNM || '' },
              { isFull: true, label: '流域名称', value: data.BSNM || '' },
              { isFull: true, label: '站类', value: data.STTP_TEXT || '' },
              { isFull: true, label: '报讯等级', value: data.FRGRD || '' },
              { isFull: true, label: '至河口距离（km）', value: data.DSTRVM || '' },
              { isFull: true, label: '集水面积（km²）', value: data.DRNA || '' },
              // { isFull: true, label: '地理位置', value: getCoordinateString([116, 27]) },
              // { isLine: true },
              { isFull: true, isMultipleLine: true, label: '站址', value: data.STLC || '' }
            ],
            hasCalculate: this.$route.path.includes('/achievements')
            // imageList: ['http://dev.beiktech.com:8600/profile/upload/common/20230721/a5c3-2e9c3a6562fa67d638860404ff9a981c_F1682314089796231168.jpg']
          }
          this.createHtmlAndShow(model, feature)
        }
      }
      if (deselected && deselected.length && selected.length === 0) {
        this.clearSelectStyle()
      }
    },
    async createHtmlAndShow ({ title, data, imageList, hasCalculate }, feature) {
      let html = `
        <div class="map-card d-flex-c full-box">
          <div class="map-card-header flex-between">
            <span class="text-ellipsis" style="flex: 0 0 1; padding-right:30px;" title="${title}">${title}</span>
          </div>
          <div class="map-card-content">
            <div class="flex-wrap">
      `
      for (const cell of data) {
        if (cell.isLine) {
          html += '<div class="dashed-line"></div>'
        } else {
          html += `
            <div class="info-cell${cell.isFull ? ' is-full' : ''}">
              <span class="info-label">${cell.label}：</span>
              <span class="info-value ${cell.isMultipleLine ? 'text-ellipsis-2' : 'text-ellipsis'}" title="${cell.value}">${cell.value}</span>
            </div>
          `
        }
      }
      html += '</div>'
      if (imageList && imageList.length) {
        html += `
        <div class="image-title-label">
          示意图：
        </div>
        <div class="image-list">
        `
        let index = 0
        for (const img of imageList.slice(0, 3)) {
          const arr = img.split('.')
          const cover = arr.slice(0, arr.length - 1).join('.') + '_THUMB.' + arr[arr.length - 1]
          this.$store.commit('map/setPopupImgList', imageList)
          html += `
            <img src="${cover}" class="img" alt="图片丢失" onclick="window.$attachment.openPopupImgByIndex(${index})" />
          `
          index++
        }
        html += '</div>'
      }
      if (hasCalculate) {
        const data = feature.getProperties()
        if (data.geometry) {
          delete data.geometry
        }
        sessionStorage.setItem('stationInfo', JSON.stringify(data))
        html += `
        <div class="m-b-mini ta-r">
          <el-button size="mini" type="primary" onclick="window.$attachment.calculateStation()" style="color: #028df7;cursor: pointer;text-decoration: underline;">计算</el-button>
        </div>
        `
      }
      html += '</div></div>'
      this.openPopup(feature.getGeometry().getCoordinates(), html)
    },
    // 设置蒙层边界
    async setMaskBoundary (layerId, feature) {
      const { geometry } = feature.getProperties()
      const isGeometry = geometry instanceof window.ol.geom.MultiPolygon
      const maskLayer = this.map1.mapUtil.getLayer(layerId)
      if (!maskLayer || !geometry || !isGeometry) return
      const nowZoom = this.map1.getView().getZoom()
      this.setCenterAndZoom(geometry.flatCoordinates, nowZoom)
      maskLayer && maskLayer.getSource().clear()
      const extent = window.turf.bboxPolygon([-180, -90, 180, 90])
      const geoJson = this.$mapManager.getMapComponent().map1.bkol.feature2GeoJson(feature)
      const maskFeature = this.$mapManager.getMapComponent().map1.bkol.geoJson2feature(
        window.turf.difference(extent, geoJson)
      )
      maskFeature.setStyle(new window.ol.style.Style({
        fill: new window.ol.style.Fill({ color: '#0000003d' }),
        stroke: new window.ol.style.Stroke({ color: '#003064', width: 2 })
      }))
      feature.setProperties({ isHighLight: true })
      maskLayer.getSource().addFeature(maskFeature)
    },
    // map1地图点击处理方法 - 目前只用在监测大屏部分
    // 无法判断点击图层 - 通过是否存在某图层判断子系统
    async mapClickCallback (evt) {
      const areaLayer = await this.map1.mapUtil.getLayer('ysqjcdp_area')
      const { coordinate } = evt
      // if (!areaLayer) return
      if (areaLayer) {
        const [feature] = areaLayer.getSource().getFeaturesAtCoordinate(coordinate)
        if (!feature) return
        const { isHighLight } = feature.getProperties()
        // console.log('mapClickCallback', { isHighLight, feature })
        if (isHighLight) {
          const maskLayer = this.map1.mapUtil.getLayer('ysqjcdp_mask')
          maskLayer && maskLayer.getSource().clear()
          this.clearSelectedFeatures()
          feature.setProperties({ isHighLight: false })
          this.setZoom('quanmao')
        } else {
          this.setMaskBoundary('ysqjcdp_mask', feature)
        }
      }
    }
  }
}
